#include "cmsis_os2.h"
#include <stdio.h>
#include <string.h>

#define BUFFER_LEN 50
#define QUEUE_SIZE 5

osMessageQueueId_t g_queue;

void send_Entry(void *argument)
{
    uint32_t i = 0;
    osStatus_t status;
    char abuf[] = "test is message x";
    uint32_t len = sizeof(abuf);

    while (i < 5) {
        abuf[len - 2] = '0' + i;
        i++;

        status = osMessageQueuePut(g_queue, abuf, 0, 0);
        if (status != osOK) {
            printf("send message failure, error: %d\n", status);
        }

        osDelay(5);  // 5 ms delay
    }
}

void recv_Entry(void *argument)
{
    osStatus_t status;
    char readBuf[BUFFER_LEN] = {0};

    while (1) {
        status = osMessageQueueGet(g_queue, readBuf, NULL, 0);
        if (status != osOK) {
            printf("recv message failure, error: %d\n", status);
            break;
        }

        printf("recv message: %s\n", readBuf);
        osDelay(5);
    }

    osMessageQueueDelete(g_queue);
    printf("delete the queue success!\n");
}

int main(void)
{
    osKernelInitialize();  // 初始化CMSIS-RTOS

    // 创建消息队列
    g_queue = osMessageQueueNew(QUEUE_SIZE, BUFFER_LEN, NULL);
    if (g_queue == NULL) {
        printf("create queue failure.\n");
        return -1;
    }
    printf("create the queue success!\n");

    // 创建发送任务
    osThreadAttr_t sendAttr = {
        .name = "sendQueue",
        .priority = osPriorityNormal,
        .stack_size = 1024
    };
    if (osThreadNew(send_Entry, NULL, &sendAttr) == NULL) {
        printf("create send task failed\n");
        return -1;
    }

    // 创建接收任务
    osThreadAttr_t recvAttr = {
        .name = "recvQueue",
        .priority = osPriorityBelowNormal,
        .stack_size = 1024
    };
    if (osThreadNew(recv_Entry, NULL, &recvAttr) == NULL) {
        printf("create recv task failed\n");
        return -1;
    }

    osKernelStart();  // 启动调度器
    return 0;
}
